from pymongo import MongoClient
import csv

class ConvertData():
    def csv_to_mongo_default(self, file, db, coll, host="localhost"):
        data = self.read_csv(file)
        self.client = MongoClient(host)
        self.col = self.client[db][coll]
        if len(data) > 0:
            self.col.insert_many(data)
        else:
            print("no data, insert nothing")

    def csv_to_mongo(self, file, db, coll, host="localhost"):
        data = self.read_csv(file)
        self.client = MongoClient(host)
        self.col = self.client[db][coll]
        ## if we can sure the need remove list is the last one
        newerdata = self.col.find().sort("date")
        if newerdata.count() > 0:
            print("we will remove item ", data[len(data)-1]["date"])
            del data[len(data)-1]
        if len(data) > 0:
            self.col.insert_many(data)
        else:
            print("no data, insert nothing")

    def csv_to_mongo_no_remove(self, file, db, coll, host="localhost"):
        data = self.read_csv(file)
        self.client = MongoClient(host)
        self.col = self.client[db][coll]
        if len(data) > 0:
            self.col.insert_many(data)
        else:
            print("no data, insert nothing")

    def read_csv(self, file):
        csv_rows = []
        with open(file) as csvfile:
            reader = csv.DictReader(csvfile)
            title = reader.fieldnames
            for row in reader:
                csv_rows.extend([{title[i]: row[title[i]] for i in range(len(title))}])

        return csv_rows
